package cms.common.exception;



import cms.common.data.ResultCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 * 功能说明：业务服务异常
 * </pre>
 *
 * @author moueimei
 * @version 1.0
 */
public class ServiceException extends BaseException {

    /**
     * 错误详细信息
     */
    private List<String> detail;

    private Object[] params;

    public ServiceException(ResultCode resultCode) {
        super(resultCode.getCode(),resultCode.getMessage());
        setDetail(resultCode.getMessage());
    }

    public ServiceException setDetail(String detail) {
        if (this.detail == null) {
            this.detail = new ArrayList<String>();
        }
        this.detail.add(detail);
        return this;
    }

    public ServiceException(int code, String message) {
        super(code,message);
    }

    public ServiceException(int code, Throwable throwable) {
        super(throwable);
        super.code = code;
    }

    public <T extends ServiceException> T addDetail(String detail) {
        if (this.detail == null) {
            this.detail = new ArrayList<String>();
        }
        this.detail.add(detail);
        return (T)this;
    }

    public <T extends ServiceException> T addDetail(List<String> detail) {
        if (detail == null) {
            return (T)this;
        }
        if (this.detail == null) {
            this.detail = detail;
        } else {
            this.detail.addAll(detail);
        }
        return (T)this;
    }

    public <T extends ServiceException> T addDetail(String[] detail) {
        if (detail == null) {
            return (T)this;
        }
        if (this.detail == null) {
            this.detail = Arrays.asList(detail);
        } else {
            this.detail.addAll(Arrays.asList(detail));
        }
        return (T)this;
    }

    public String joinDetail() {
        if (detail == null || detail.size() == 0) {
            return null;
        }
        if (detail.size() == 1) {
            return detail.get(0);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String item : detail) {
            stringBuilder.append("，").append(item);
        }
        return stringBuilder.substring(1);
    }

    public String getMsg() {
        return joinDetail();
    }



    public String toString(){
        return "code:" + code + ", msg:" + getMessage() + ",detail:[" + joinDetail() + "]";
    }
}

